<template>
	<fui-nav-bar title="消息"></fui-nav-bar>
	<!-- <fui-tabs :tabs="tabs" isDot scroll alignLeft></fui-tabs>
	<fui-list>
		<fui-list-cell :highlight="false" class="dazCard" @click="goToDazDetail">
			<image src="../../static/1.jpg" mode=""></image>
			<view class="info">
				<view>
					<text style="font-weight: bold">搭子名称：</text>
					<text>张梦曦</text>
				</view>
				<view style="margin: 10rpx 0rpx">
					<text style="font-weight: bold">搭子简介：</text>
					<text>
						本人诚实，热情，具有良好的人际关系，极富创造力与创新意识，具有较强的逻辑思维和组织协调能力，对事情认真，负责，有很强的责任心和团队精神，为人自信，乐观，处事冷静，服从领导安排，吃苦耐劳等。
					</text>
				</view>
			</view>
		</fui-list-cell>
	</fui-list -->
	<!-- 消息列表 -->
	<fui-empty v-show="conversationList.length === 0" src="../../static/empty-icon/Conversation.png" title="暂无会话" width="100" height="100" size="20"></fui-empty>
	<template v-for="(item, index) of conversationList" :key="item.userID">
		<view
			class="item-box"
			@click="chatStore.chatHandler(item.conversationID, item.avatar, item.remark, item.userID)"
			@longpress="onLongPress(item.conversationID, item.isPinned)"
		>
			<!-- 头像 -->
			<view class="avatar">
				<fui-avatar width="110" :src="item.avatar || '/static/1.jpg'"></fui-avatar>
				<div v-if="isOnline !== 'other'" :class="['status', isOnline === 'on' ? 'status-online' : 'status-offline']"></div>
			</view>
			<!-- 名字时间等 -->
			<view class="col-2">
				<view class="row-1">
					<view class="name">{{ item.remark || item.userID }}</view>
					<view class="time">
						<view class="pin-status" v-show="item.isPinned">^置顶</view>
						<uni-dateformat date="2024-09-23 15:06:34" :threshold="[60000, 3600000 * 24]" format="M/d"></uni-dateformat>
					</view>
				</view>
				<view class="chat-content">{{ item.type === 'TIMTextElem' ? item.messageForShow : '其他类型消息' }}</view>
			</view>
		</view>
	</template>
	<fui-backdrop :show="show" closable @click="close">
		<view class="inner-box">
			<button @click="pinkHandler">{{ isPinned ? '取消置顶' : '置顶' }}</button>
			<button @click="deleteConversation">删除会话</button>
		</view>
	</fui-backdrop>
	<!-- <button @click="openConversation">打开会话列表</button> -->
	<button @click="getConversation">获取会话列表</button>
	<!-- <button @click="openConcat">打开联系人</button> -->
	<!-- <button @click="send">发送</button> -->
	<!-- <tabbar></tabbar> -->
</template>

<script>
import { TUILogin } from '@tencentcloud/tui-core';
import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import { defineComponent, reactive, toRefs, ref, onMounted } from 'vue';
// #ifdef APP-PLUS || H5
import { TUIChatKit } from '@/TUIKit/index.ts';
// #endif
import { onLoad, onShow } from '@dcloudio/uni-app';
import { useUserStore } from '../../store/user';
import { getChatRecordApi, getUserSigApi } from '@/request/modules/chat.js';
import { showMsg } from '../../utils/interact';
import useChatStore from '../../store/chat';

export default defineComponent({
	name: 'daz',
	setup() {
		const data = reactive({
			conversationList: [],
			isOnline: 'on',
			show: false,
			isPinned: false
		});
		// 仓库变量
		const chatStore = useChatStore();
		// 非响应式变量
		let userID = '5';
		let appId = 1600051499;
		let userSig =
			'eJyrVgrxCdZLrSjILEpVsjI0NTU1MjAw0AGLlqUWKVkpGekZKEH4xSnZiQUFmSlAdWZARaaGJpaWEJnMlNS8ksy0TLAGU5jyzHQgr6q4MNzY2zgv3NzLKNfTvcKs0NA81d3Yx9Ivz9Q1Lz0iKSTfNN1Iu8rEwMAWqrEkMxfkFnMjM3NLcwMD81oAG9kulA__';
		let tim = null;
		let totalUnreadCount = 0;
		let conversationID;
		// #ifdef APP-PLUS || H5
		TUIChatKit.init();
		// #endif
		// 事件回调
		const openConversation = () => {
			uni.navigateTo({
				url: '/TUIKit/components/TUIConversation/index'
			});
		};
		const openConcat = () => {
			uni.navigateTo({
				url: '/TUIKit/components/TUIContact/index'
			});
		};

		//长按显示删除和置顶，取消置顶
		const onLongPress = (convID, isPinned) => {
			data.isPinned = isPinned;
			conversationID = convID;
			data.show = true;
		};

		const close = () => {
			data.show = false;
		};
		//置顶或取消置顶
		const pinkHandler = () => {
			tim.pinConversation({
				conversationID,
				isPinned: !data.isPinned
			})
				.then((res) => {
					getConversation();
				})
				.catch((err) => {
					console.error(err);
					if (data.isPinned) {
						showMsg('取消置顶失败，请重试');
					} else {
						showMsg('置顶失败，请重试');
					}
				});
		};
		//删除会话
		const deleteConversation = () => {
			tim.deleteConversation(conversationID)
				.then((res) => {
					console.log('删除成功:', res);
					getConversation();
				})
				.catch((err) => {
					showMsg('删除失败');
					console.log('删除失败：', err);
				});
		};
		const getConversation = () => {
			if (tim.isReady()) {
				tim.getConversationList()
					.then((res) => {
						// console.log(res.data.conversationList);
						data.conversationList = res.data.conversationList.map((con) => {
							let {
								userProfile: { avatar, userID },
								conversationID,
								lastMessage: { lastTime, type, payload, messageForShow },
								isPinned,
								unreadCount,
								remark
							} = con;
							const newObj = {
								avatar,
								userID,
								conversationID,
								unreadCount, //未读消息数
								lastTime,
								type,
								messageForShow,
								isPinned,
								payload,
								remark
							};
							return newObj;
						});
						// console.log(data.conversationList);
						/* 	getChatRecordApi({ fromUserId: '5', toUserId: '2', maxCnt: 5 })
              	.then((res) => {
              		console.log(res);
              	})
              	.catch((err) => {
              		console.log(err);
              	}); */
					})
					.catch((err) => {
						console.log(err);
					});
			}
		};

		onLoad(() => {
			/* 	TUILogin.login({
        	SDKAppID: appId,
        	userID,
        	userSig,
        	useUploadPlugin: true,
        	framework: 'vue3'
        })
        	.then(() => {
        		console.log('登录tim成功');
        	})
        	.catch((err) => {
        		console.error(err);
        	}); */
		});
		onShow(() => {
			totalUnreadCount = tim.getTotalUnreadMessageCount();
			console.log('退出聊天界面时：', totalUnreadCount);
			if (totalUnreadCount > 0) {
				uni.setTabBarBadge({
					index: 2,
					text: totalUnreadCount + ''
				});
			} else {
				uni.removeTabBarBadge({
					index: 2
				});
			}
		});
		const onConversationListUpdated = (event) => {
			console.log('会话列表更新了');
		};
		const sdkReady = () => {
			console.log('sdk已就绪');
			// 获取所有会话的未读消息总数
			totalUnreadCount = tim.getTotalUnreadMessageCount();
			if (totalUnreadCount > 0) {
				uni.setTabBarBadge({
					index: 2,
					text: totalUnreadCount + ''
				});
			}
		};
		// 所有会话未读消息总数发生变化
		const onTotalUnreadMessageCountUpdated = (event) => {};
		// 收到消息
		const onMessageReceived = (event) => {
			console.log('收到了：', event);
			totalUnreadCount = tim.getTotalUnreadMessageCount();
			if (totalUnreadCount > 0) {
				uni.setTabBarBadge({
					index: 2,
					text: totalUnreadCount + '',
					fail() {
						console.log('失败');
					}
				});
				getConversation();
			}
		};
		// 组件生命周期
		onMounted(() => {
			// 创建IM sdk实例
			tim = TencentCloudChat.create({
				SDKAppID: 1600051499
			});
			// 监听sdk READY事件
			tim.on(TencentCloudChat.EVENT.SDK_READY, sdkReady);
			// 监听所有会话的未读消息数发生变化
			tim.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, onTotalUnreadMessageCountUpdated);
			// 监听收到消息事件
			tim.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
			// 监听会话列表更新事件
			tim.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, onConversationListUpdated);
			tim.setLogLevel(0); //设置日志级别为普通级别
			// tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
			// 注册上传插件
			tim.registerPlugin({
				'tim-upload-plugin': TIMUploadPlugin
			});

			//登录im后台
			/* tim.login({
        	userID,
        	userSig
        })
        	.then((res) => {
        		console.log('登录im成功');
        	})
        	.catch((err) => {
        		console.log(err);
        	}); */
		});
		//请求接口
		return {
			...toRefs(data),
			openConversation,
			openConcat,
			getConversation,
			chatStore,
			onLongPress,
			close,
			pinkHandler,
			deleteConversation
		};
	}
});
</script>

<style scoped lang="scss">
/* .dazCard {
	display: flex;
	image {
		width: 200rpx;
		height: 250rpx;
	}
	.info {
		width: calc(100% - 200rpx);
		height: 250rpx;
		padding: 10rpx 20rpx 10rpx 20rpx;
		box-sizing: border-box;
		font-size: 24rpx;
	}
} */
.inner-box {
	width: 60vw;
}

.item-box {
	width: 750rpx;
	font-size: 12px;
	padding: 20px 10px;
	color: $uni-text-color-placeholder;
	display: flex;

	.avatar {
		position: relative;

		.status {
			box-sizing: border-box;
			width: 10px;
			height: 10px;
			position: absolute;
			z-index: 99;
			bottom: 15px;
			right: 4px;
			border: 2px solid #fff;
			border-radius: 50%;
			box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);

			&-online {
				background-color: #3dfc3d;
			}

			&-offline {
				background-color: gray;
			}
		}
	}

	.col-2 {
		width: calc(100% - 100rpx);
		padding: 4px 0 10px 10px;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.row-1 {
			width: 100%;
			display: flex;
			justify-content: space-between;

			.name {
				font-size: 18px;
				color: #333;
			}
			.time {
				display: flex;
				align-items: center;
				.pin-status {
					margin-right: 10px;
				}
			}
		}
	}
}
</style>
